package com.jhsw.roadsun.module.business.service.useraddress;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jhsw.roadsun.framework.common.pojo.PageResult;
import com.jhsw.roadsun.framework.common.util.object.BeanUtils;
import com.jhsw.roadsun.module.business.controller.admin.useraddress.vo.UserAddressPageReqVO;
import com.jhsw.roadsun.module.business.controller.app.useraddress.vo.AppUserAddressPageReqVO;
import com.jhsw.roadsun.module.business.controller.app.useraddress.vo.AppUserAddressRespVO;
import com.jhsw.roadsun.module.business.controller.app.useraddress.vo.UserAddressSaveReqVO;
import com.jhsw.roadsun.module.business.dal.dataobject.useraddress.UserAddressDO;
import com.jhsw.roadsun.module.business.dal.mysql.useraddress.UserAddressMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.Objects;

import static com.jhsw.roadsun.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jhsw.roadsun.module.business.enums.ErrorCodeConstants.NO_PERMISSION;
import static com.jhsw.roadsun.module.business.enums.ErrorCodeConstants.USER_ADDRESS_NOT_EXISTS;

/**
 * 地址簿 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class UserAddressServiceImpl implements UserAddressService {

    @Resource
    private UserAddressMapper userAddressMapper;

    @Override
    public void deleteUserAddress(Long id) {
        // 校验存在
        validateUserAddressExists(id);
        // 删除
        userAddressMapper.deleteById(id);
    }

    private UserAddressDO validateUserAddressExists(Long id) {
        UserAddressDO userAddressDO = userAddressMapper.selectById(id);
        if (userAddressDO == null)
            throw exception(USER_ADDRESS_NOT_EXISTS);
        return userAddressDO;
    }

    @Override
    public UserAddressDO getUserAddress(Long id) {
        return userAddressMapper.selectById(id);
    }

    @Override
    public PageResult<UserAddressDO> getUserAddressPage(UserAddressPageReqVO pageReqVO) {
        return userAddressMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional
    public Long createUserAddress(UserAddressSaveReqVO createReqVO, Long userId) {
        createReqVO.setId(null);
        // 判断当前地址是否是默认的，若是，则设置其他地址为非默认
        Boolean isNormal = createReqVO.getIsNormal();
        if (Objects.nonNull(isNormal) && isNormal)
            userAddressMapper.update(Wrappers.<UserAddressDO>lambdaUpdate()
                    .eq(UserAddressDO::getUserId, userId).eq(UserAddressDO::getType, createReqVO.getType())
                    .set(UserAddressDO::getIsNormal, 0));

        // 插入
        UserAddressDO userAddress = BeanUtils.toBean(createReqVO, UserAddressDO.class);
        userAddress.setUserId(userId);
        userAddressMapper.insert(userAddress);

        // 返回
        return userAddress.getId();
    }

    @Override
    public void updateUserAddress(UserAddressSaveReqVO updateReqVO, Long userId) {
        // 校验存在
        UserAddressDO userAddressDO = validateUserAddressExists(updateReqVO.getId());

        // 判断是否是当前用户的地址簿
        if (!userId.equals(userAddressDO.getUserId()))
            throw exception(NO_PERMISSION);

        // 判断当前地址是否是默认的，若是，则设置其他地址为非默认
        Boolean isNormal = updateReqVO.getIsNormal();
        if (Objects.nonNull(isNormal) && isNormal)
            userAddressMapper.update(Wrappers.<UserAddressDO>lambdaUpdate()
                    .eq(UserAddressDO::getUserId, userId).eq(UserAddressDO::getType, updateReqVO.getType())
                    .set(UserAddressDO::getIsNormal, 0));

        // 更新
        UserAddressDO updateObj = BeanUtils.toBean(updateReqVO, UserAddressDO.class);
        userAddressMapper.updateById(updateObj);
    }

    @Override
    public void appDeleteUserAddress(Long id, Long userId) {
        // 校验存在
        UserAddressDO userAddressDO = validateUserAddressExists(id);

        // 判断是否是当前用户的地址簿
        if (!userId.equals(userAddressDO.getUserId()))
            throw exception(NO_PERMISSION);

        userAddressMapper.deleteById(id);
    }

    @Override
    public PageResult<AppUserAddressRespVO> appGetUserAddressPage(AppUserAddressPageReqVO pageReqVO, Long userId) {
        return userAddressMapper.appGetUserAddressPage(pageReqVO, userId);
    }

    @Override
    public AppUserAddressRespVO getUserNormalAddress(Integer type, Long userId) {
        UserAddressDO userAddressDO = userAddressMapper.selectOne(Wrappers.<UserAddressDO>lambdaQuery()
                .eq(UserAddressDO::getUserId, userId)
                .eq(UserAddressDO::getType, type)
                .eq(UserAddressDO::getIsNormal, 1)
                .last("LIMIT 1"));
        return BeanUtils.toBean(userAddressDO, AppUserAddressRespVO.class);
    }

    @Override
    public Long selectCountByUserId(Long userId, int type) {
        return userAddressMapper.selectCountByUserId(userId, type);
    }
}